package com.flyduck.vueshop.system.manager;

import com.alibaba.fastjson.JSON;
import com.flyduck.vueshop.common.redis.utils.RedisUtils;
import com.flyduck.vueshop.system.constant.SysConstant;
import com.flyduck.vueshop.system.entity.SysUser;
import com.flyduck.vueshop.system.mapper.SysUserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * SysPermissionManager
 * </p>
 *
 * @author flyduck
 * @since 2024-05-29
 */
@Slf4j
@Component
public class SysPermissionCacheManager {

    @Autowired
    private SysPermissionManager sysPermissionManager;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private RedisUtils redisUtils;

    public List<String> getPermissionListByUserId(Long userId) {
        List<String> permissionList = new ArrayList<>();
        if(redisUtils.hasKey(SysConstant.RedisConstant.USER_PERMISSIONS_KEY + userId)){
            log.info("缓存命中【查询用户操作权限】");
            String authoritiesString = (String) redisUtils.get(SysConstant.RedisConstant.USER_PERMISSIONS_KEY + userId);
            permissionList = JSON.parseArray(authoritiesString, String.class);
        }else {
            log.info("缓存未命中【查询用户操作权限】");
            permissionList = sysPermissionManager.getPermissionListByUserId(userId);
            redisUtils.set(SysConstant.RedisConstant.USER_PERMISSIONS_KEY + userId,
                    JSON.toJSONString(permissionList),
                    SysConstant.RedisConstant.USER_PERMISSIONS_EXPIRE);
        }
        return permissionList;
    }

    public void clearPermissionListByUserId(Long userId){
        redisUtils.del(SysConstant.RedisConstant.USER_PERMISSIONS_KEY + userId);
    }

    public void clearPermissionListByRoleId(Long roleId){
        List<SysUser> sysUserList = sysUserMapper.getUserListByRoleId(roleId);
        sysUserList.forEach(sysUser -> {
            this.clearPermissionListByUserId(sysUser.getId());
        });
    }

    public void clearPermissionListByMenuId(Long menuId){
        List<SysUser> sysUserList = sysUserMapper.getUserListByMenuId(menuId);
        sysUserList.forEach(sysUser -> {
            this.clearPermissionListByUserId(sysUser.getId());
        });
    }
}
